package com.campus.lostandfound.controller;

import com.campus.lostandfound.common.Result;
import com.campus.lostandfound.entity.Permission;
import com.campus.lostandfound.entity.Role;
import com.campus.lostandfound.entity.User;
import com.campus.lostandfound.service.AdminService;
import com.campus.lostandfound.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 超级管理员Controller
 */
@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 检查当前用户是否为超级管理员
     */
    private Long checkSuperAdmin(String token) {
        String userId = jwtUtil.getUserIdFromToken(token);
        User user = getUserByUserId(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!adminService.isSuperAdmin(user.getId())) {
            throw new RuntimeException("无权访问,仅超级管理员可操作");
        }
        return user.getId();
    }
    
    /**
     * 辅助方法:根据userId查询用户
     */
    private User getUserByUserId(String userId) {
        List<User> allUsers = adminService.getAllUsers();
        return allUsers.stream()
                .filter(u -> userId.equals(u.getUserId()))
                .findFirst()
                .orElse(null);
    }
    
    // ==================== 用户管理 ====================
    
    /**
     * 获取所有用户列表（包含RBAC角色信息）
     */
    @GetMapping("/users")
    public Result<List<Map<String, Object>>> getAllUsers(@RequestHeader("Authorization") String token) {
        try {
            checkSuperAdmin(token);
            List<User> users = adminService.getAllUsers();
            
            // 为每个用户添加 RBAC 角色信息
            List<Map<String, Object>> usersWithRoles = users.stream().map(user -> {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("id", user.getId());
                userMap.put("userId", user.getUserId());
                userMap.put("username", user.getUsername());
                userMap.put("password", null); // 不返回密码
                userMap.put("salt", null); // 不返回盐值
                userMap.put("studentNo", user.getStudentNo());
                userMap.put("phone", user.getPhone());
                userMap.put("email", user.getEmail());
                userMap.put("role", user.getRole());
                userMap.put("status", user.getStatus());
                userMap.put("violationCount", user.getViolationCount());
                userMap.put("createTime", user.getCreateTime());
                
                // 获取用户的 RBAC 角色
                List<Role> roles = adminService.getUserRoles(user.getId());
                List<String> roleCodes = roles.stream()
                        .map(Role::getRoleCode)
                        .collect(Collectors.toList());
                List<String> roleNames = roles.stream()
                        .map(Role::getRoleName)
                        .collect(Collectors.toList());
                
                userMap.put("roleCodes", roleCodes);
                userMap.put("roleNames", roleNames);
                
                return userMap;
            }).collect(Collectors.toList());
            
            return Result.success(usersWithRoles);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 启用用户
     */
    @PostMapping("/user/enable/{userId}")
    public Result<String> enableUser(@RequestHeader("Authorization") String token,
                                     @PathVariable Long userId) {
        try {
            checkSuperAdmin(token);
            adminService.enableUser(userId);
            return Result.success("启用用户成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 禁用用户
     */
    @PostMapping("/user/disable/{userId}")
    public Result<String> disableUser(@RequestHeader("Authorization") String token,
                                      @PathVariable Long userId) {
        try {
            checkSuperAdmin(token);
            adminService.disableUser(userId);
            return Result.success("禁用用户成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/user/{userId}")
    public Result<String> deleteUser(@RequestHeader("Authorization") String token,
                                     @PathVariable Long userId) {
        try {
            checkSuperAdmin(token);
            adminService.deleteUser(userId);
            return Result.success("删除用户成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 为用户分配角色
     * 限制：不允许分配超级管理员角色（超级管理员角色只能由xxc拥有）
     */
    @PostMapping("/user/assign-role")
    public Result<String> assignRoleToUser(@RequestHeader("Authorization") String token,
                                           @RequestBody Map<String, Long> params) {
        try {
            checkSuperAdmin(token);
            Long userId = params.get("userId");
            Long roleId = params.get("roleId");
            
            // 检查是否试图分配超级管理员角色
            // roleId=1 对应 SUPER_ADMIN 角色
            if (roleId == 1) {
                return Result.error("不允许分配超级管理员角色。系统只允许xxc拥有超级管理员权限。");
            }
            
            adminService.assignRoleToUser(userId, roleId);
            return Result.success("分配角色成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 移除用户角色
     * 限制：不允许移除xxc的超级管理员角色
     */
    @PostMapping("/user/remove-role")
    public Result<String> removeUserRole(@RequestHeader("Authorization") String token,
                                         @RequestBody Map<String, Long> params) {
        try {
            checkSuperAdmin(token);
            Long userId = params.get("userId");
            Long roleId = params.get("roleId");
            
            // 检查是否试图移除超级管理员角色
            // roleId=1 对应 SUPER_ADMIN 角色
            if (roleId == 1) {
                return Result.error("不允许移除超级管理员角色。系统必须保留xxc的超级管理员权限。");
            }
            
            adminService.removeUserRole(userId, roleId);
            return Result.success("移除角色成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户的角色列表
     */
    @GetMapping("/user/{userId}/roles")
    public Result<List<Role>> getUserRoles(@RequestHeader("Authorization") String token,
                                           @PathVariable Long userId) {
        try {
            checkSuperAdmin(token);
            List<Role> roles = adminService.getUserRoles(userId);
            return Result.success(roles);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户的权限列表
     */
    @GetMapping("/user/{userId}/permissions")
    public Result<List<Permission>> getUserPermissions(@RequestHeader("Authorization") String token,
                                                       @PathVariable Long userId) {
        try {
            checkSuperAdmin(token);
            List<Permission> permissions = adminService.getUserPermissions(userId);
            return Result.success(permissions);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    // ==================== 角色管理 ====================
    
    /**
     * 获取所有角色列表
     */
    @GetMapping("/roles")
    public Result<List<Role>> getAllRoles(@RequestHeader("Authorization") String token) {
        try {
            checkSuperAdmin(token);
            List<Role> roles = adminService.getAllRoles();
            return Result.success(roles);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 添加角色
     */
    @PostMapping("/role")
    public Result<String> addRole(@RequestHeader("Authorization") String token,
                                  @RequestBody Role role) {
        try {
            checkSuperAdmin(token);
            adminService.addRole(role);
            return Result.success("添加角色成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/role/{roleId}")
    public Result<String> deleteRole(@RequestHeader("Authorization") String token,
                                     @PathVariable Long roleId) {
        try {
            checkSuperAdmin(token);
            adminService.deleteRole(roleId);
            return Result.success("删除角色成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新角色
     */
    @PutMapping("/role")
    public Result<String> updateRole(@RequestHeader("Authorization") String token,
                                     @RequestBody Role role) {
        try {
            checkSuperAdmin(token);
            adminService.updateRole(role);
            return Result.success("更新角色成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 为角色分配权限
     */
    @PostMapping("/role/assign-permission")
    public Result<String> assignPermissionToRole(@RequestHeader("Authorization") String token,
                                                 @RequestBody Map<String, Long> params) {
        try {
            checkSuperAdmin(token);
            Long roleId = params.get("roleId");
            Long permissionId = params.get("permissionId");
            adminService.assignPermissionToRole(roleId, permissionId);
            return Result.success("分配权限成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 移除角色权限
     */
    @PostMapping("/role/remove-permission")
    public Result<String> removeRolePermission(@RequestHeader("Authorization") String token,
                                               @RequestBody Map<String, Long> params) {
        try {
            checkSuperAdmin(token);
            Long roleId = params.get("roleId");
            Long permissionId = params.get("permissionId");
            adminService.removeRolePermission(roleId, permissionId);
            return Result.success("移除权限成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取角色的权限列表
     */
    @GetMapping("/role/{roleId}/permissions")
    public Result<List<Permission>> getRolePermissions(@RequestHeader("Authorization") String token,
                                                       @PathVariable Long roleId) {
        try {
            checkSuperAdmin(token);
            List<Permission> permissions = adminService.getRolePermissions(roleId);
            return Result.success(permissions);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    // ==================== 权限管理 ====================
    
    /**
     * 获取所有权限列表
     */
    @GetMapping("/permissions")
    public Result<List<Permission>> getAllPermissions(@RequestHeader("Authorization") String token) {
        try {
            checkSuperAdmin(token);
            List<Permission> permissions = adminService.getAllPermissions();
            return Result.success(permissions);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 添加权限
     */
    @PostMapping("/permission")
    public Result<String> addPermission(@RequestHeader("Authorization") String token,
                                       @RequestBody Permission permission) {
        try {
            checkSuperAdmin(token);
            adminService.addPermission(permission);
            return Result.success("添加权限成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除权限
     */
    @DeleteMapping("/permission/{permissionId}")
    public Result<String> deletePermission(@RequestHeader("Authorization") String token,
                                          @PathVariable Long permissionId) {
        try {
            checkSuperAdmin(token);
            adminService.deletePermission(permissionId);
            return Result.success("删除权限成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新权限
     */
    @PutMapping("/permission")
    public Result<String> updatePermission(@RequestHeader("Authorization") String token,
                                          @RequestBody Permission permission) {
        try {
            checkSuperAdmin(token);
            adminService.updatePermission(permission);
            return Result.success("更新权限成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}

